package com.briup.smartcity_group6.service.Impl;

import com.briup.smartcity_group6.bean.basic.BaseConfig;
import com.briup.smartcity_group6.dao.basic.BaseConfigMapper;
import com.briup.smartcity_group6.dao.ext.BaseConfigExtMapper;
import com.briup.smartcity_group6.exception.ServiceException;
import com.briup.smartcity_group6.service.IBaseConfigService;
import com.briup.smartcity_group6.utils.ResultCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BaseConfigServiceImpl implements IBaseConfigService {
    Integer m=1;//用来确认状态，最小限制或者启用
    @Autowired
    private BaseConfigMapper mapper;
    @Autowired
    private BaseConfigExtMapper extMapper;

    //保存设置
    @Override
    public void saveConfig(BaseConfig baseConfig) {
        mapper.insert(baseConfig);
    }
    @Override
    public void updateConfig(BaseConfig baseConfig) {
        //防止恶意修改状态
        baseConfig.setConfigStatus(null);
        mapper.updateByPrimaryKeySelective(baseConfig);
    }
    @Override
    public PageInfo<BaseConfig> findAllWithPage(int pageNum, int pageSize) {

        PageInfo<BaseConfig> pageInfo = PageHelper.startPage(pageNum, pageSize, true).doSelectPageInfo(
                () -> extMapper.selectAll()
        );
        return pageInfo;
    }
    @Override
    public BaseConfig currentConfigYes() {
        return extMapper.selectYes();
    } //返回当前启用的配置信息
    @Override
    public void deleteById(int id) {
        if (extMapper.count()==m){
            throw new ServiceException(ResultCode.DLM);
        }
        BaseConfig baseConfig = mapper.selectByPrimaryKey(id);
        if (baseConfig.getConfigStatus()==m){
            throw new ServiceException(ResultCode.DLE);
        }
        mapper.deleteByPrimaryKey(id);
    }
    @Override
    public void changeConfigStatus(int id, int status) {
//改变配置状态 0为状态未启用
        if (status == 0){
            throw new ServiceException(ResultCode.SLM);
        }
        //开启一个配置信息并关闭当前配置
        if (status == 1){ //如果状态启用
            //那么关闭旧的配置
            BaseConfig enabledBaseConfig = extMapper.selectYes();
            enabledBaseConfig.setConfigStatus(0);
            mapper.updateByPrimaryKeySelective(enabledBaseConfig);
            //然后打开需要的配置信息
            BaseConfig toEnabledBaseConfig  = mapper.selectByPrimaryKey(id);
            toEnabledBaseConfig.setConfigStatus(status);
            mapper.updateByPrimaryKeySelective(toEnabledBaseConfig);
        }
    }

}
